import axios from 'axios';
import { Message } from '@alicloudfe/components';
import envConfig from './config';

/**
 * 错误处理(依赖http状态码)
 * @httpCode http状态码
 * @data 返回数据
 */
const errorHandleByHttp = (httpCode: number, data: any) => {
  switch (httpCode) {
    default:
      if (httpCode > 500) {
        Message.warning('系统错误');
        return;
      }
      Message.warning(data.error_message);
      break;
  }
};

const service = axios.create({
  baseURL: envConfig.apiHost, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 15000, // request timeout
});

// request interceptor
service.interceptors.request.use(
  (config) => {
    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);

// response interceptor
service.interceptors.response.use(
  (response) => {
    const newRes = response;
    const resData = newRes.data;

    return resData;
  },
  (error) => {
    const { status, data } = error.response;
    errorHandleByHttp(status, data);
    return Promise.reject(error.response);
  },
);

export default service;
